import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


class Message{
    public String from;
    public String to;
    public String message;
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这个方法来处理"获取所有留言消息"
        //需要返回一个json字符串数组，Jackson直接帮我们处理好了格式。
        //创建一个load方法从数据库中加载数据，传递给messageList对象
        List<Message> messageList = load();
        String respString = objectMapper.writeValueAsString(messageList);
        //这个list中的每一个元素，就是数组中的每一个元素。
        resp.setContentType("application/json;charset=utf8");
        //最后将Jason字符串整体返回响应即可
        resp.getWriter().write(respString);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这个方法来处理"提交新消息"
        //通过这个方法，将提交的信息按照Message类的格式解析 ，用message对象接收
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        save(message);
        System.out.println("消息提交成功 message=" + message);

        //响应只是返回200报文，body为空，此时不需熬额外处理，默认就是返回200.
    }

    //使用这个方法从数据库中查询所有所有记录
    private List<Message> load()  {
        List<Message> messageList = new ArrayList<>();
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/message_wall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("991218zf");

        try{
            //建立连接
            Connection connection = dataSource.getConnection();
            String sql = "select * from message";
            PreparedStatement statement = connection.prepareStatement(sql);
            //执行这个sql语句
            ResultSet resultSet = statement.executeQuery();

            while(resultSet.next()){
                Message message = new Message();
                //这里参数中from与列名中的from是匹配的
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messageList.add(message);
            }
            resultSet.close();
            statement.close();
            connection.close();
        }catch(SQLException e){
            e.printStackTrace();
        }
        return messageList;
    }
    //使用这个方法向数据库中存入一条记录
    private void save(Message message)  {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/message_wall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("991218zf");

        try{
            //建立连接
            Connection connection = dataSource.getConnection();
            String sql = "insert into message values(?,?,?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.message);
            //执行这个sql语句
            statement.executeUpdate();
            statement.close();
            connection.close();
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
}
